<template>
  <div class="form-body" >
    <!-- 返回按钮 -->
    <a-button 
      type="primary" 
      class="back-button" 
      @click="handleBack"
    >
      Return to Adult Membership Application
    </a-button>
  <div class="background-image"></div>
  <div v-if="authStore.isAuthenticated" class="form-container">

    <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" @finish="handleSubmit">

      <!-- SRU编号 -->
      <a-form-item label="SRU Number" name="sruNumber" :rules="[{ required: true, message: 'Please enter SRU number!' }]">
        <a-input v-model:value="formState.sruNumber" placeholder="Automatically generated SRU number" :disabled="true" />
      </a-form-item>

      <!-- 地址 -->
      <a-form-item label="Address" name="address" :rules="[{ required: true, message: 'Please select an address!' }]">
        <a-select v-model:value="formState.address" placeholder="Please select a Scottish region" show-search option-filter-prop="label">
          <a-select-option v-for="area in scottishAreas" :key="area.value" :value="area.value" :label="area.label">
            {{ area.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 出生日期 -->
      <a-form-item label="Date of Birth" name="birthDate" :rules="[{ required: true, message: 'Please select a date of birth!' }]">
        <a-date-picker v-model:value="formState.birthDate" value-format="YYYY-MM-DD" style="width: 100%" />
      </a-form-item>

      <!-- 电话号码 -->
      <a-form-item label="Phone Number" name="phoneNumber" :rules="[{ required: true, message: 'Please enter a phone number!' }]">
        <a-input v-model:value="formState.phoneNumber" placeholder="Please enter a phone number" />
      </a-form-item>

      <!-- 手机号码 -->
      <a-form-item label="Mobile Number" name="mobileNumber" :rules="[{ required: true, message: 'Please enter a mobile number!' }]">
        <a-input v-model:value="formState.mobileNumber" placeholder="Please enter a mobile number" />
      </a-form-item>

      <!-- 邮政编码 -->
      <a-form-item label="Postal Code" name="zipCode" :rules="[{ required: true, message: 'Please enter a postal code!' }]">
        <a-input v-model:value="formState.zipCode" placeholder="Will be automatically filled based on the region" :disabled="true" />
      </a-form-item>

      <!-- 邮箱 -->
      <a-form-item label="Email" name="email" :rules="[{ required: true, type: 'email', message: 'Please enter a valid email address!' }]">
        <a-input v-model:value="formState.email" placeholder="Please enter an email" />
      </a-form-item>

      <!-- 新增监护人1信息 -->
      <a-form-item label="Guardian 1 Name" name="guardian1Name" :rules="[{ required: true, message: 'Please enter Guardian 1 name!' }]">
        <a-input v-model:value="formState.guardian1Name" placeholder="Please enter Guardian 1 name" />
      </a-form-item>

      <a-form-item label="Guardian 1 Phone Number" name="guardian1PhoneNumber" :rules="[{ required: true, message: 'Please enter Guardian 1 phone number!' }]">
        <a-input v-model:value="formState.guardian1PhoneNumber" placeholder="Please enter Guardian 1 phone number" />
      </a-form-item>

      <a-form-item label="Guardian 1 Address" name="guardian1Address" :rules="[{ required: true, message: 'Please enter Guardian 1 address!' }]">
        <a-input v-model:value="formState.guardian1Address" placeholder="Please enter Guardian 1 address" />
      </a-form-item>

      <!-- 新增监护人2信息 -->
      <a-form-item label="Guardian 2 Name" name="guardian2Name" :rules="[{ required: true, message: 'Please enter Guardian 2 name!' }]">
        <a-input v-model:value="formState.guardian2Name" placeholder="Please enter Guardian 2 name" />
      </a-form-item>

      <a-form-item label="Guardian 2 Phone Number" name="guardian2PhoneNumber" :rules="[{ required: true, message: 'Please enter Guardian 2 phone number!' }]">
        <a-input v-model:value="formState.guardian2PhoneNumber" placeholder="Please enter Guardian 2 phone number" />
      </a-form-item>

      <a-form-item label="Guardian 2 Address" name="guardian2Address" :rules="[{ required: true, message: 'Please enter Guardian 2 address!' }]">
        <a-input v-model:value="formState.guardian2Address" placeholder="Please enter Guardian 2 address" />
      </a-form-item>
      <!-- 新增就诊医生 -->
      <a-form-item label="Doctor" name="doctor" :rules="[{ required: true, message: 'Please enter doctor name!' }]">
        <a-input v-model:value="formState.doctor" placeholder="Please enter doctor name" />
      </a-form-item>

      <!-- 新增医生电话 -->
      <a-form-item label="Doctor Phone Number" name="doctorPhoneNumber" :rules="[{ required: true, message: 'Please enter doctor phone number!' }]">
        <a-input v-model:value="formState.doctorPhoneNumber" placeholder="Please enter doctor phone number" />
      </a-form-item>

      <!-- 新增医生地址 -->
      <a-form-item label="Doctor Address" name="doctorAddress" :rules="[{ required: true, message: 'Please enter doctor address!' }]">
        <a-input v-model:value="formState.doctorAddress" placeholder="Please enter doctor address" />
      </a-form-item>

      <!-- 新增已知健康问题 -->
      <a-form-item label="Known Health Issues" name="knownHealthIssues" :rules="[{ required: true, message: 'Please enter known health issues!' }]">
        <a-textarea v-model:value="formState.knownHealthIssues" placeholder="Please enter known health issues (e.g., allergies, chronic diseases, etc.)" :rows="4" />
      </a-form-item>

      <!-- 提交按钮 -->
      <a-form-item :wrapper-col="{ offset: 6, span: 14 }">
        <a-button type="primary" html-type="submit">Submit</a-button>
      </a-form-item>
    </a-form>
  </div>
  <a-alert v-else class="no-data" type="warning" show-icon>
    <template #message>
      You must log in/register to apply for a minor membership.
    </template>
    <template #description>
      You will be redirected to the login page in {{ countdown }} seconds...
    </template>
  </a-alert>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue';
import { message ,Modal} from 'ant-design-vue';
import { useRouter } from 'vue-router';
import axios from "../axios";
import { useAuthStore } from '../store/auth';
import { generateSRUNumberFromToken } from '../utils/tokenUtils'; // 引入工具函数

const countdown = ref(5); // 倒计时初始值
const authStore = useAuthStore();
const router = useRouter();

// 定义表单状态
const formState = reactive({
  sruNumber: '',
  address: '',
  birthDate: '',
  phoneNumber: '',
  mobileNumber: '',
  zipCode: '',
  email: '',
  guardian1Name: '',     
  guardian1PhoneNumber: '', 
  guardian1Address: '',  
  guardian2Name: '',     
  guardian2PhoneNumber: '', 
  guardian2Address: '',  
  doctorAddress: ''  ,
  doctor: '',
  doctorPhoneNumber: '', 
  knownHealthIssues: '',    
});

// 表单提交处理
const handleSubmit = async () => {
  try {
    const response = await axios.post('/minor_members', formState);
    message.success('The application for underage member has been successful!');
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    // console.log(axiosError.response);
    if (axiosError.response?.data?.code === 401) {
      message.error(axiosError.response.data.message || 'The username or password is incorrect.');
    } else if (axiosError.response?.data?.code === 400) {
      message.error(axiosError.response.data.message || 'Verification code error, please try again.');// 刷新验证码
    } else {
      message.error('Login failed, please try again.');
    }
    message.error('Submission failed, please check the input or contact the administrator!');
  }
};
// 返回按钮点击事件
const handleBack = () => {
  Modal.confirm({
        title: 'reminder',
        content: 'Do you want to return the adult membership application',
        okText: 'confirm',
        cancelText: 'cancel',
        onOk() {
          // 用户确认后跳转
          router.push({ name: 'MemberApplication' });
        },
        onCancel() {
          message.info('Cancelled return');
        },
      });
  
};
// 监听出生日期变化，判断是否为未成年
watch(() => formState.birthDate, (newBirthDate) => {
  if (newBirthDate) {
    const age = calculateAge(newBirthDate);
    if (age >= 18) {
      // 显示确认对话框
      Modal.confirm({
        title: 'Detected adult users',
        content: 'The date of birth you entered indicates that you are an adult. Are you sure you want to redirect to the adult membership application page? If selected incorrectly, please click cancel to re-enter.',
        okText: 'confirm',
        cancelText: 'cancel',
        onOk() {
          // 用户确认后跳转
          router.push({ name: 'MemberApplication' });
        },
        onCancel() {
          // 用户取消后清空出生日期
          formState.birthDate = '';
          message.info('Birth date has been cleared, please re-enter.');
        },
      });
    }
  }
});

// 计算年龄函数
function calculateAge(birthDate: string): number {
  const today = new Date();
  const birth = new Date(birthDate);
  let age = today.getFullYear() - birth.getFullYear();
  const monthDifference = today.getMonth() - birth.getMonth();
  if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
}


// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
  if (!isAuthenticated) {
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        router.push({ name: 'Auth' });
      }
    }, 1000);
  }
}, { immediate: true }); // 立即执行

// 监听地址变化
watch(() => formState.address, (newVal) => {
  const selectedArea = scottishAreas.find(area => area.value === newVal);
  if (selectedArea) {
    formState.zipCode = selectedArea.postcode;
    // 可以添加更精确的示例：formState.zipCode = `${selectedArea.postcode}1 1${Math.floor(Math.random()*9)}Z`;
  }
});
// 苏格兰行政区列表参考
const scottishAreas = reactive([
  { value: 'aberdeen-city', label: 'Aberdeen City', postcode: 'AB10-AB25' },
  { value: 'edinburgh', label: 'City of Edinburgh', postcode: 'EH1-EH17' },
  { value: 'glasgow', label: 'Glasgow City', postcode: 'G1-G80' },
  { value: 'stirling', label: 'Stirling', postcode: 'FK7-FK9' },
  // 其他地区补充完整邮编前缀...
]);

onMounted(async () => {
  try {
    // 仅在已认证且token存在时执行赋值
    if (authStore.isAuthenticated && authStore.token) {
      // 使用工具函数生成 SRU 编号
      formState.sruNumber = generateSRUNumberFromToken(authStore.token);
    } else {
      // 处理未登录或token缺失的情况（如清空SRU编号）
      formState.sruNumber = '';
    }
  } catch (e) {
    message.error('User information loading failed, please try again');
  }
});

</script>

<style scoped>
.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}

.background-image {
  position: relative; /* 相对定位 */
  width: 50%; /* 固定宽度 */
  height: 800px; /* 固定高度 */
  background: url('../static/form.png') no-repeat left center; /* 图片靠左对齐 */
  background-size: auto 100%; /* 高度填满，宽度自动调整 */
}
/* 右侧表单容器 */
.form-container {
  position: absolute; /* 绝对定位，覆盖在背景图片上 */
  top: 70%; /* 垂直居中 */
  right: 40px; /* 距离右侧留出空间 */
  transform: translateY(-50%); /* 垂直居中调整 */
  width: 800px; /* 固定宽度 */
  height: 700px; /* 固定高度 */
  padding: 16px;
  background-color: rgba(255, 255, 255, 0.9); /* 半透明背景 */
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 10; /* 确保表单容器在背景图片之上 */

  /* 启用垂直滚动条 */
  overflow-y: auto;
}
/* 自定义滚动条样式 */
.form-container::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.form-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2); /* 滑块颜色 */
  border-radius: 16px; /* 滑块圆角 */
}

.form-container::-webkit-scrollbar-track {
  background-color: transparent; /* 轨道颜色 */
}
.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}
</style>